import json
from datetime import datetime
import requests
import yaml

def get_aenant_access_token(app_id,app_secret):
    retries = 0
    while retries < 3:
        try:
            headers = {
                "Content-Type": "application/json; charset=utf-8"
            }
            json = {
                "app_id": app_id,
                "app_secret": app_secret
            }
            response = requests.post(
                "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
                headers=headers,
                json=json,
                timeout=10
            )
            return response.json().get("tenant_access_token")
        except Exception as e:
            print(e)
            retries += 1

def get_up_list_by_range(access_token,spreadsheetToken,sheetId,start,end):
    '''

    :param access_token: access_token(应用或用户)
    :param spreadsheetToken: 表格token
    :param sheetId: 表格sheetId
    :param start: 范围开始
    :param end: 范围结束
    :return:
    {
    row_id : 行id，
    mid : up主mid,
    state : 状态
    }
    '''
    headers = {
        "Authorization" : f"Bearer {access_token}",
        "Content-Type": "application/json; charset=utf-8"
    }
    range = f"{sheetId}!A{start}:C{end}"
    response = requests.get(
        f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{spreadsheetToken}/values/{range}",
        headers=headers,
        # params=params,
        timeout=10
    )
    lists = response.json().get("data").get("valueRange").get("values")
    up_list = []
    cur_index = start
    for list in lists:
        if list[0] == None:
            continue
        if list[0] == "":
            continue
        up = {
            "row_id" : cur_index,
            "mid" : str(list[0]),
            "state" : str(list[1]),
            "updated_at": str(list[2])
        }
        up_list.append(up)
        cur_index += 1
    return up_list

def get_key_list_by_range(access_token,spreadsheetToken,sheetId,start,end):
    retries = 0 
    while retries < 3:
        try:
            headers = {
                "Authorization" : f"Bearer {access_token}",
                "Content-Type": "application/json; charset=utf-8"
            }
            range = f"{sheetId}!A{start}:C{end}"
            response = requests.get(
                f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{spreadsheetToken}/values/{range}",
                headers=headers,
                # params=params,
                timeout=10
            )
            lists = response.json().get("data").get("valueRange").get("values")
            keyword_list = []
            cur_index = start
            for list in lists:
                if list[0] == None:
                    continue
                if list[0] == "":
                    continue
                keyword = {
                    "row_id" : cur_index,
                    "keyword" : str(list[0]),
                    "state" : str(list[1]),
                    "updated_at": str(list[2])
                }
                keyword_list.append(keyword)
                cur_index += 1
            return keyword_list
        except Exception as e:
            print(e)
            retries += 1

def update_state_by_rowId(access_token,spreadsheetToken,sheetId,row_id,update_time):
    headers = {
        "Authorization" : f"Bearer {access_token}",
        "Content-Type": "application/json; charset=utf-8"
    }
    range = f"{sheetId}!B{row_id}:C{row_id}"
    json = {
        "valueRange":{
            "range": range,
            "values": [
            [
                "ok",
                update_time
            ],
            ]
        }
    }
    requests.put(
        f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{spreadsheetToken}/values",
        headers=headers,
        json=json,
        timeout=10
    )

def is_valid_datetime(input_str) -> bool:
    """检查字符串是否为 '%Y-%m-%d %H:%M:%S' 格式的合法时间"""
    try:
        if get_date(input_str) != get_dt():
            return False
        return True
    except:
        # 解析失败则返回False
        return False


def get_keyword_list_by_range_bilibili(access_token,spreadsheetToken,sheetId,start,end):
    retries = 0
    while retries < 3:
        try:
            headers = {
                "Authorization": f"Bearer {access_token}",
                "Content-Type": "application/json; charset=utf-8"
            }
            max_col_index = get_max_col_index(access_token, spreadsheetToken, sheetId)
            range = f"{sheetId}!A{start}:{max_col_index}{end}"
            response = requests.get(
                f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{spreadsheetToken}/values/{range}",
                headers=headers,
                # params=params,
                timeout=10
            )
            lists = response.json().get("data").get("valueRange").get("values")
            keyword_list = []
            cur_index = start
            keyword_index = get_col_index(get_col(access_token,spreadsheetToken,sheetId,"keyword_basic"))
            update_time_index = get_col_index(get_col(access_token, spreadsheetToken, sheetId, "update_time"))
            for list in lists:
                if list[keyword_index] == None:
                    cur_index += 1
                    continue
                if list[keyword_index] == "":
                    cur_index += 1
                    continue
                if is_valid_datetime(list[update_time_index]):
                    cur_index += 1
                    continue
                keyword = {
                    "row_id": cur_index,
                    "keyword": str(list[keyword_index]),
                    "update_time": str(list[update_time_index])
                }
                keyword_list.append(keyword)
                cur_index += 1

            return keyword_list
        except Exception as e:
            print(e)
            retries += 1
    return []


def get_keyword_list_by_range_douyin(access_token,spreadsheetToken,sheetId,start,end):
    retries = 0
    while retries < 3:
        try:
            headers = {
                "Authorization": f"Bearer {access_token}",
                "Content-Type": "application/json; charset=utf-8"
            }
            max_col_index = get_max_col_index(access_token, spreadsheetToken, sheetId)
            range = f"{sheetId}!A{start}:{max_col_index}{end}"
            response = requests.get(
                f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{spreadsheetToken}/values/{range}",
                headers=headers,
                # params=params,
                timeout=10
            )
            lists = response.json().get("data").get("valueRange").get("values")
            keyword_list = []
            cur_index = start
            keyword_index = get_col_index(get_col(access_token,spreadsheetToken,sheetId,"keyword"))
            update_time_index = get_col_index(get_col(access_token, spreadsheetToken, sheetId, "update_time"))
            for list in lists:
                if list[keyword_index] == None:
                    cur_index += 1
                    continue
                if list[keyword_index] == "":
                    cur_index += 1
                    continue
                if is_valid_datetime(list[update_time_index]):
                    cur_index += 1
                    continue
                keyword = {
                    "row_id": cur_index,
                    "keyword": str(list[keyword_index]),
                    "update_time": str(list[update_time_index])
                }
                keyword_list.append(keyword)
                cur_index += 1

            return keyword_list
        except Exception as e:
            print(e)
            retries += 1
    return []

def get_douyin_ttwid_from_feishu(access_token,spreadsheetToken,sheetId) -> str:
    retries = 0
    while retries < 3:
        try:
            headers = {
                "Authorization": f"Bearer {access_token}",
                "Content-Type": "application/json; charset=utf-8"
            }
            max_col_index = get_max_col_index(access_token, spreadsheetToken, sheetId)
            range = f"{sheetId}!C{2}:C{2}"
            response = requests.get(
                f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{spreadsheetToken}/values/{range}",
                headers=headers,
                # params=params,
                timeout=10
            )
            lists = response.json().get("data").get("valueRange").get("values")
            return lists[0][0]
        except Exception as e:
            print(e)
            retries += 1
    return "1%7CGeyiqrMZSUDpy5c1xp0zWF9rwg3Y6YF-Ef8tJUD-mPw%7C1750227786%7C39cc6bef46f0496130ac889a9dd8d54b9125f9e9611c374b96fc548953d17951"

def update_douyin_ttwid(access_token,spreadsheetToken,sheetId,ttwid):
    retries = 0
    while retries < 3:
        try:
            headers = {
                "Authorization": f"Bearer {access_token}",
                "Content-Type": "application/json; charset=utf-8"
            }
            ttwid_col_index = 'C'
            range = f"{sheetId}!{ttwid_col_index}{2}:{ttwid_col_index}{2}"
            json = {
                "valueRange": {
                    "range": range,
                    "values": [
                        [
                           ttwid
                        ],
                    ]
                }
            }
            requests.put(
                f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{spreadsheetToken}/values",
                headers=headers,
                json=json,
                timeout=10
            )
            return
        except Exception as e:
            print(e)
            retries += 1


def get_keyword_list_by_range_kuaishou(access_token,spreadsheetToken,sheetId,start,end):
    retries = 0
    while retries < 3:
        try:
            headers = {
                "Authorization": f"Bearer {access_token}",
                "Content-Type": "application/json; charset=utf-8"
            }
            max_col_index = get_max_col_index(access_token, spreadsheetToken, sheetId)
            range = f"{sheetId}!A{start}:{max_col_index}{end}"
            response = requests.get(
                f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{spreadsheetToken}/values/{range}",
                headers=headers,
                # params=params,
                timeout=10
            )
            lists = response.json().get("data").get("valueRange").get("values")
            keyword_list = []
            cur_index = start
            keyword_index = get_col_index(get_col(access_token,spreadsheetToken,sheetId,"keyword"))
            update_time_index = get_col_index(get_col(access_token, spreadsheetToken, sheetId, "update_time"))
            for list in lists:
                if list[keyword_index] == None:
                    cur_index += 1
                    continue
                if list[keyword_index] == "":
                    cur_index += 1
                    continue
                if is_valid_datetime(list[update_time_index]):
                    cur_index += 1
                    continue
                keyword = {
                    "row_id": cur_index,
                    "keyword": str(list[keyword_index]),
                    "update_time": str(list[update_time_index])
                }
                keyword_list.append(keyword)
                cur_index += 1

            return keyword_list
        except Exception as e:
            print(e)
            retries += 1
    return []


def get_keyword_list_by_range_xiaohongshu(access_token,spreadsheetToken,sheetId,start,end):
    retries = 0
    while retries < 3:
        try:
            headers = {
                "Authorization": f"Bearer {access_token}",
                "Content-Type": "application/json; charset=utf-8"
            }
            max_col_index = get_max_col_index(access_token, spreadsheetToken, sheetId)
            range = f"{sheetId}!A{start}:{max_col_index}{end}"
            response = requests.get(
                f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{spreadsheetToken}/values/{range}",
                headers=headers,
                # params=params,
                timeout=10
            )
            lists = response.json().get("data").get("valueRange").get("values")
            keyword_list = []
            cur_index = start
            keyword_index = get_col_index(get_col(access_token,spreadsheetToken,sheetId,"keyword"))
            update_time_index = get_col_index(get_col(access_token, spreadsheetToken, sheetId, "update_time"))
            for list in lists:
                if list[keyword_index] == None:
                    cur_index += 1
                    continue
                if list[keyword_index] == "":
                    cur_index += 1
                    continue
                if is_valid_datetime(list[update_time_index]):
                    cur_index += 1
                    continue
                keyword = {
                    "row_id": cur_index,
                    "keyword": str(list[keyword_index]),
                    "update_time": str(list[update_time_index])
                }
                keyword_list.append(keyword)
                cur_index += 1

            return keyword_list
        except Exception as e:
            print(e)
            retries += 1
    return []



def get_dt():
    return str(datetime.now().date())

def get_date(date_str):
    # 将字符串解析为datetime对象
    dt = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
    # 提取日期部分并格式化为字符串
    return str(dt.strftime("%Y-%m-%d"))

def get_col_index(col):
    return ord(col) - ord('A')

def get_max_col_index(access_token,spreadsheetToken,sheetId):
    retries = 0
    while retries < 3:
        try:
            headers = {
                "Authorization": f"Bearer {access_token}",
                "Content-Type": "application/json; charset=utf-8"
            }
            range = f"{sheetId}!A1:K1"
            response = requests.get(
                f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{spreadsheetToken}/values/{range}",
                headers=headers,
                # params=params,
                timeout=10
            )
            lists = response.json().get("data").get("valueRange").get("values")
            col_N = 'A'
            for col in lists[0]:
                if col == None:
                    break
                if col == "":
                    break

                col_N = chr(ord(col_N) + 1)

            return chr(ord(col_N) - 1)
        except Exception as e:
            print(e)
            retries += 1

def update_time_by_rowId(access_token,spreadsheetToken,sheetId,row_id,update_time):
    retries = 0
    while retries < 3:
        try:
            headers = {
                "Authorization": f"Bearer {access_token}",
                "Content-Type": "application/json; charset=utf-8"
            }
            # update_time_col_index = get_col(access_token, spreadsheetToken, sheetId, "update_time")
            update_time_col_index = 'B'
            range = f"{sheetId}!{update_time_col_index}{row_id}:{update_time_col_index}{row_id}"
            json = {
                "valueRange": {
                    "range": range,
                    "values": [
                        [
                            update_time
                        ],
                    ]
                }
            }
            requests.put(
                f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{spreadsheetToken}/values",
                headers=headers,
                json=json,
                timeout=10
            )
            return
        except Exception as e:
            print(e)
            retries += 1


def get_col(access_token,spreadsheetToken,sheetId,col_name):
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Content-Type": "application/json; charset=utf-8"
    }
    range = f"{sheetId}!A1:K1"
    retries = 0
    while retries < 3:
        try:
            response = requests.get(
                f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{spreadsheetToken}/values/{range}",
                headers=headers,
                # params=params,
                timeout=10
            )
            lists = response.json().get("data").get("valueRange").get("values")
            # col_list = []
            col_N = 'A'
            for col in lists[0]:
                if col == None:
                    continue
                if col == "":
                    continue
                # item = {
                #     "col_name" : col,
                #     "col_index" : col_N
                # }
                if col == col_name:
                    return col_N
                col_N = chr(ord(col_N) + 1)
                # col_list.append(item)
            return None
        except Exception as e:
            retries += 1
            print(e)
            continue
    return None

def get_app_token(access_token,node_token):
    retries = 0
    while retries < 3:
        try:
            headers = {
                "Authorization": f"Bearer {access_token}",
                "Content-Type": "application/json; charset=utf-8"
            }
            params = {
                "token": node_token
            }
            response = requests.get(
                f"https://open.feishu.cn/open-apis/wiki/v2/spaces/get_node",
                headers=headers,
                params=params,
                timeout=10
            )
            return response.json().get("data").get("node").get("obj_token")
        except Exception as e:
            print(e)
            retries += 1

def load_config():
    """
    从YAML配置文件加载配置

    Returns:
        dict: 配置字典
    """
    try:
        with open('./common/config.yaml', 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)
        return config
    except Exception as e:
        print(e)
        # 直接退出程序
        import sys
        sys.exit(1)

config = load_config()

def sendToFeishu(message):
    url = "https://open.feishu.cn/open-apis/bot/v2/hook/d9e6c29b-9a0b-4376-95d3-4abac30f2e83"
    headers = {
        "Content-Type": "application/json"
    }
    data = {
        "msg_type": "text",
        "content": {
            "text": message
        }
    }
    response = requests.post(url, headers=headers, data=json.dumps(data))
    return response.json()


def main():
    # print(is_valid_datetime("2025-04-24 10:23:29"))
    # sendToFeishu("test")

    # print(str(get_date("2025-04-24 10:23:29")))
    app_id = config.get("app_id")
    app_serect = config.get("app_serect")
    sheet_keyword_list = config.get("sheet_keyword_list")
    access_token = get_aenant_access_token(app_id, app_serect)
    node_token = config.get("node_token")
    app_token = get_app_token(access_token,node_token)

    # print(get_keyword_list_by_range_v2(access_token,app_token,sheet_keyword_list,2,100))
    # print(get_col(access_token,app_token,sheet_keyword_list,"keyword_basic"))

    update_time_by_rowId(access_token,app_token,sheet_keyword_list,"2","2025-04-24 10:23:29")
if __name__ == "__main__":
    print(get_keyword_list_by_range_bilibili(2,100))